<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #relateOtherPassage="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="20" :md="20" :lg="20" :xl="20">
            <ApiSelect
              :api="listCanRelatedPassage"
              placeholder="未引用"
              :params="requestParams"
              :immediate="immediate"
              @select="(value, opt) => selectRelatePassage(model, field, value)"
              :allowClear="true"
              showSearch
              @clear="clearSelectRelatedPassage(model, field)"
              :value="model[field]"
              optionFilterProp="label"
              resultField="data"
              labelField="wayName"
              valueField="id"
            />
          </a-col>
          <a-col :sm="4" :md="4" :lg="4" :xl="4">
            <a-button :disabled="!model[field]" type="primary" style="width: 100%" @click="goRelatePassage">去配置</a-button>
          </a-col>
        </a-row>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, ApiSelect, useForm } from "/@/components/Form/index"
  import { formSchema } from "./payPassage.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdatePayPassage, getPayPassage } from "/@/api/pay"
  import { listCanRelatedPassage } from "/@/api/pay"
  import { Modal } from "ant-design-vue"

  const emit = defineEmits(["success", "register", "go-relate-passage"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  const payPassageRecord = ref<any>({})
  const mchAppRecord = ref<any>({})
  const requestParams = ref<any>({})
  const immediate = ref(false)
  const relateId = ref()

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, getFieldsValue, resetSchema }] = useForm({
    layout: "vertical",
    labelWidth: "100%",
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const clearSelectRelatedPassage = async (model, field) => {
    relateId.value = undefined
    await initFormSchema()
    model[field] = undefined
  }

  const selectRelatePassage = async (model, field, value) => {
    // let oldValues = await getFieldsValue();
    let schemas: any = []
    schemas.push.apply(schemas, formSchema)
    resetSchema(schemas)

    console.log(">>> selectRelatePassage", value)
    relateId.value = value
    model[field] = value
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true })
    try {
      const { payPassage } = data.record
      await resetFields()
      const respData = (await getPayPassage({ id: payPassage.id })) || { canRelate: true }
      payPassageRecord.value = {
        ...payPassage,
        ...respData,
      }
      relateId.value = respData.relateId

      requestParams.value = {
        excludeWayCode: payPassageRecord.value.wayCode,
        appId: payPassage.appId,
        ifCode: payPassage.ifCode,
      }

      mchAppRecord.value = data.record.mchApp
      console.log("payPassage: ", payPassageRecord.value)

      let showFooter = data?.showFooter ?? true
      setDrawerProps({ confirmLoading: false, showFooter })
      isUpdate.value = !!data?.isUpdate

      await initFormSchema()
      immediate.value = true
      setProps({ disabled: !showFooter })
    } finally {
      setDrawerProps({ loading: false })
    }
  })
  const getTitle = computed(() => (!unref(isUpdate) ? `新增支付通道` : `编辑支付通道【${payPassageRecord.value.wayName}】`))

  const initFormSchema = async () => {
    const { ifName, wayName, mchParamsDefine, channelParams = "{}" } = payPassageRecord.value

    // 判断是否将配置参数作用于支付方式上
    if (mchParamsDefine && !relateId.value) {
      let schemas: any = []
      schemas.push.apply(schemas, formSchema)
      schemas.push({
        field: ifName + "-" + wayName + "-divider",
        component: "Divider",
        label: wayName + " 配置",
      })
      let paramsDefine: any[] = JSON.parse(mchParamsDefine)
      paramsDefine.forEach((e) => {
        schemas.push({
          field: `params_${e.field}`,
          label: e.label,
          show: e.show === undefined || e.show ? true : false,
          required: e.required ? e.required : false,
          componentProps: e.componentProps,
          helpMessage: e.helpMessage,
          defaultValue: e.defaultValue,
          component: e.component,
        })
      })
      await resetSchema(schemas)
    }

    if (typeof payPassageRecord.value === "object") {
      const newChannelParamsObj = {}
      const originalChannelParams = JSON.parse(channelParams)
      for (const key in originalChannelParams) {
        newChannelParamsObj["params_" + key] = originalChannelParams[key]
      }

      let values = await getFieldsValue()
      for (const key in values) {
        if (!values[key]) {
          delete values[key]
        }
      }
      await setFieldsValue({
        ...payPassageRecord.value,
        ...newChannelParamsObj,
        ...values,
      })
    }
  }
  async function handleSubmit() {
    try {
      let values = await validate()
      values.id = payPassageRecord.value.id
      values.appId = mchAppRecord.value.id
      values.wayCode = payPassageRecord.value.wayCode
      values.ifCode = payPassageRecord.value.ifCode

      const channelParams = {}
      for (const key in values) {
        if (key.startsWith("params_")) {
          channelParams[key.replaceAll("params_", "")] = values[key]
          delete values[key]
        }
      }
      console.log("submit: ", values, channelParams)

      setDrawerProps({ confirmLoading: true })

      await saveOrUpdatePayPassage({ ...values, channelParams: JSON.stringify(channelParams) })
      closeDrawer()
      emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const goRelatePassage = async () => {
    setDrawerProps({ loading: true })
    try {
      const oldValue = payPassageRecord.value
      let newValues = await getFieldsValue()
      const relatePassage = await getPayPassage({ id: newValues.relateId })
      console.log("oldValue: ", oldValue, ", newValues: ", newValues)
      for (const key in newValues) {
        if (!key.startsWith("params_") && newValues[key] && newValues[key] !== oldValue[key]) {
          Modal.confirm({
            title: "确认保存",
            content: "当前数据已变更, 是否确认保存",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
              await handleSubmit()
              emit("go-relate-passage", relatePassage)
            },
            onCancel: () => {
              if (key === "relateId") {
                return
              }
              closeDrawer()
              emit("go-relate-passage", relatePassage)
            },
          })
          return
        }
      }
      closeDrawer()
      emit("go-relate-passage", relatePassage)
    } finally {
      setDrawerProps({ loading: false })
    }
  }
</script>
